package com.freesun.shop.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.freesun.shop.config.AliPayConfig;
import com.freesun.shop.domin.Pay;
import com.freesun.shop.service.AliPayService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

@Service
public class AliPayServiceImpl implements AliPayService {
    private static Logger log = LoggerFactory.getLogger(AliPayServiceImpl.class);
    @Autowired
    private AlipayTradeService tradeService;

    @Autowired
    private AlipayClient alipayClient;

    private static final String PUBLIC_NET_URL="http://ego.free.idcfengye.com/pay/%s";
    @Override
    public String prePay(Pay pay) {
        Assert.notNull(pay,"支付的订单信息不能为Null");
        Assert.notNull(pay.getPayType(),"支付的方式不能为Null");
        switch (pay.getPayType()) {
            case 0: //电脑支付
                return computerPay(pay);
            case 1: //扫码支付
                return f2fPay(pay);
                default:
                    throw new RuntimeException("暂未支持的支付方式:"+pay.getPayType());
        }
    }

    private String f2fPay(Pay pay) {
        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(pay.getSubject()).setTotalAmount(pay.getTotalAmount()).setOutTradeNo(pay.getOutTradeNo())
                .setUndiscountableAmount(pay.getUndiscountableAmount()).setSellerId(pay.getSellerId()).setBody(pay.getBody())
                .setOperatorId(pay.getOperatorId()).setStoreId(pay.getStoreId())
                .setTimeoutExpress(pay.getTimeoutExpress())
        .setNotifyUrl(String.format(PUBLIC_NET_URL,pay.getOutTradeNo()));//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置

        //向支付宝的支付网关发起请求
        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {  //得到响应结果
            case SUCCESS:
                log.info("支付宝预下单成功: )");

                AlipayTradePrecreateResponse response = result.getResponse();
                // 需要修改为运行机器上的路径
//                String filePath = String.format("D:/qr-%s.png",
//                        response.getOutTradeNo());
//                log.info("filePath:" + filePath);
//                //                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);
                return response.getQrCode();

            case FAILED:
                log.error("支付宝预下单失败!!!");
                break;

            case UNKNOWN:
                log.error("系统异常，预下单状态未知!!!");
                break;

            default:
                log.error("不支持的交易状态，交易返回异常!!!");
                break;
        }
        return null;
    }

    private String computerPay(Pay pay){
        //获得初始化的AlipayClient

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.return_url);
        alipayRequest.setNotifyUrl(AliPayConfig.notify_url);


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ pay.getOutTradeNo() +"\","
                + "\"total_amount\":\""+ pay.getTotalAmount() +"\","
                + "\"subject\":\""+ pay.getSubject() +"\","
                + "\"body\":\""+ pay.getBody() +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        System.out.println(result);
        return result;
    }
}
